import router from "@/router";
import {defineStore} from 'pinia';
import type {Router, RouteRecordRaw} from 'vue-router';
import defaultSettings from '@/settings'
import {generateMainRoute} from "./main-menu";

const defLogo = 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg';
const {sideTheme, showSettings, topNav, tagsView, fixedHeader, sidebarLogo, dynamicTitle} = defaultSettings

const buildRouteInfo = (router: Router, routes: RouteRecordRaw[], parent: any = undefined) => {
    routes.forEach(m => {
        if (parent) {
            router.addRoute(parent.name, m);
        } else {
            router.addRoute(m);
        }

        if (m.children && m.children.length > 0) {
            buildRouteInfo(router, m.children, m);
        }
    })
}

const findRouteByPath = (path: string, data: Array<RouteRecordRaw>) => {
    let result: any = undefined;
    for (const item of data) {
        if (item.path === path) {
            return item;
        }

        if (item.children && item.children.length > 0) {
            result = findRouteByPath(path, item.children);
            if (result) {
                return result;
            }
        }
    }

    return result;
}

const findFirstChildRouteByPath = (path: string, data: Array<RouteRecordRaw>) => {
    let result: any = undefined;
    for (const item of data) {
        if (item.path.startsWith(path)) {
            return item;
        }

        if (item.children && item.children.length > 0) {
            result = findFirstChildRouteByPath(path, item.children);
            if (result) {
                return result;
            }
        }
    }

    return result;
}

const findFirstRouteLeaf = (routeItem: any) => {
    let result: any = undefined;
    if (routeItem.meta.type === 0 &&
        routeItem.children && routeItem.children.length > 0) {
        result = findFirstRouteLeaf(routeItem.children[0]);
    } else {
        result = routeItem;
    }

    return result;
}

export const useStore: any = defineStore('store', {
    state: () => {
        return {
            sidebar: {
                opened: true,
                withoutAnimation: false,
                hide: false,
            } as Record<string, any>,
            platform: undefined,
            settings: {
                title: '统一认证平台前端框架',
                logo: defLogo,
                theme: '#409EFF',
                sideTheme: sideTheme,
                menuMode: 'one',
                copyRight: '2016-2024 小码资讯科技有限公司',
            } as Record<string, any>,
            menus: [] as Array<MenuType>,
            products: {} as Record<string, any>,
            // 路由表
            routes: [] as Array<RouteRecordRaw>,
            currents: {} as Record<string, any>,
            activeMenu: {} as Record<string, string>,
            currentWatch: {} as Record<string, any>,
            userAssets: {} as Record<string, any>,
            userData: {} as Record<string, any>,
            homeRoute: '',
            hasRouted: false,
            topMenuMap: {} as Record<string, any>,
            topRouteMap: {} as Record<string, any>,
            currentTopName: '' as string,
        }
    },
    getters: {
        getCurrentPlatform: (state) => {
            return () => {
                return state.platform;
            }
        },
        getSettings: (state: any) => {
            return () => {
                return state.settings;
            }
        },
        hasBuildRoute: (state: any) => {
            return () => {
                return state.hasRouted;
            }
        },
        getMenuRoute: (state: any) => {
            return () => {
                return state.routes;
            }
        },
        getHomeRoute: (state: any) => {
            return () => {
                return state.homeRoute;
            }
        },
        getMenus: (state: any) => {
            return () => {
                return state.menus;
            }
        },
        getSubMenus: (state: any) => {
            return (name: string | undefined = undefined) => {
                const path = name || router.currentRoute.value.path;
                const menus = state.menus;
                return menus.find(item => item.routePath.toLowerCase() === path.toLowerCase())?.children || [];
            }
        },
        getTopMenus: (state: any) => {
            return () => {
                const menus: MenuType[] = [];
                state.menus.forEach(item => {
                    if (!state.topMenuMap) {
                        menus.push(item);
                    } else {
                        if (!Object.entries(state.topMenuMap).find((mm: any) => mm.name === item.name)) {
                            menus.push(item);
                        }
                    }
                });
                return menus;
            }
        },
        getCurrent: (state: any) => {
            return (name: string) => {
                return state.currents[name];
            }
        },
        getCurrentWatch: (state: any) => {
            return (name: string) => {
                return state.currentWatch[name];
            }
        },
        getActiveMenu: (state: any) => {
            return (name: string) => {
                return state.activeMenu[name];
            }
        },
        getUserAssets: (state: any) => {
            return () => {
                return state.userAssets;
            }
        },
        getUserMenu: (state: any) => {
            return () => {
                return state.userAssets ? state.userAssets.menus : [];
            }
        },
        getUser: (state: any) => {
            return () => {
                return state.userData?.user || {};
            }
        },
        getUserPermits: (state) => {
            return () => {
                return state.userAssets ? state.userAssets.permitCodes : [];
            }
        },
        getCredential: (state: any) => {
            return () => {
                return state.userData?.cred || {};
            }
        },

        getCurrentTopName: (state: any) => {
            return () => {
                return state.currentTopName || '';
            }
        },
    },
    actions: {
        buildRouteMenus(mainLay: any, data: MenuType[], defPage: string) {
            this.menus = data;

            this.homeRoute = defPage;
            this.routes = generateMainRoute(mainLay, this, data);
        },
        // 添加动态路由，并同步到状态管理器中
        buildRoutes(data: any, router: Router) {
            this.hasRouted = true;
            buildRouteInfo(router, this.routes);
        },
        setCurrentPlatform(pl: any) {
            this.platform = pl;
        },
        updateCurrent(name: string, item: any, tag: string) {
            this.currents[name] = {
                tag: tag,
                item: item,
            };
        },
        updateActiveMenu(name: string, val: any) {
            this.activeMenu[name] = val;
        },
        updateUserAssets(assets: any) {
            this.userAssets = assets;
        },
        setUserData(data: any): void {
            this.userData = data;
        },
        setTopMenuMap(data: any): void {
            this.topMenuMap = data;
        },
        addTopMenuMap(name: string, data: any): void {
            this.topMenuMap[name] = data;
        },
        updateCurrentTopName(currRoute: string) {
            this.currentTopName = currRoute;
        },
        getTopRouteInfo(path: any) {
            const pos = path.substring(2).indexOf('/');
            const rootPath = -1 == pos ? path : path.substring(0, pos + 2);
            let currTop = this.topRouteMap[rootPath];

            if (!currTop) {
                currTop = {
                    leaf: '',
                    current: ''
                }
                this.topRouteMap[rootPath] = currTop;
            }

            return {
                rootPath: rootPath,
                currTop: currTop,
            }
        },
        updateTopRoute(path: any) {
            const result = {
                path: '',
                name: ''
            };
            const {rootPath, currTop} = this.getTopRouteInfo(path);

            // 如果还没初始化，初始化为第一个路由叶子节点
            if (!currTop.leaf) {
                const currRoute = findRouteByPath(rootPath, this.routes);
                if (currRoute) {
                    const leaf = findFirstRouteLeaf(currRoute);
                    if (leaf) {
                        currTop.leaf = leaf.path;
                    }
                    if (!currTop.current || currTop.leaf === rootPath) {
                        currTop.current = currTop.leaf;
                    }
                }
            }

            let skipPath;

            // 如果点击了根路由
            if (path === rootPath) {
                // 这个顶层路由没有子路由（本身就是叶子节点）
                skipPath = rootPath != currTop.leaf ? currTop.current : '';
            } else {
                currTop.current = path;
                if (!currTop.leaf) {
                    currTop.leaf = path;
                }
            }

            result.path = skipPath;
            result.name = rootPath.substring(1);

            return result;
        },
        updateTopFirstRoute(path: any) {
            if (this.settings.menuMode != 'second') {
                return;
            }

            const result = {
                path: '',
                name: ''
            };
            const {rootPath, currTop} = this.getTopRouteInfo(path);

            if (!currTop.leaf) {
                const currRoute = findFirstChildRouteByPath(rootPath, this.routes);

                if (currRoute) {
                    currTop.leaf = currRoute.path;
                    if (!currTop.current) {
                        currTop.current = currTop.leaf;
                    }
                }
            } else if (path !== rootPath) {
                currTop.current = path;
            }

            result.path = currTop.current;
            result.name = rootPath.substring(1);

            return result;
        }
    },
});
